package com.jml.zookeeper.一期.Java操作ZK;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
public class Java操作ZK {
	//zk连接地址
	private static final String connectString = "127.0.0.1:2181";
	//session超时时间
	private static final int sessionTimeOut = 5000;
	//信号量,阻塞程序执行,用户等待zookeeper连接成功,发送成功信号，1表示计数器
	private static final CountDownLatch countDownLatch = new CountDownLatch(1);

	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
		ZooKeeper zk = new ZooKeeper(connectString, sessionTimeOut, new Watcher() {
			public void process(WatchedEvent event) {
				// 获取事件状态
				KeeperState keeperState = event.getState();
				// 获取事件类型
				EventType eventType = event.getType();
				if (KeeperState.SyncConnected == keeperState) {
					if (EventType.None == eventType) {
						//会将计数器-1，如果为0就会通知等待方运行
						countDownLatch.countDown();
						System.out.println("zk 启动连接...");
					}
					if (EventType.NodeCreated == eventType) {
						System.out.println("zk 事件通知，获取当前创建的节点...");
					}

				}
			}
		});
		// 进行阻塞   如果计数器不为0就会一直等待
		countDownLatch.await();

		String path = "/jml_Lasting";
		//为true表示允许有事件通知
		zk.exists(path,true);

		String result = zk.create(path, "Lasting".getBytes(), Ids.OPEN_ACL_UNSAFE,
				CreateMode.PERSISTENT_SEQUENTIAL);
		System.out.println(result);
		Thread.sleep(2000);
		zk.close();
	}
}
